package net.qqxh.controller;

import net.qqxh.persistent.JfSysUserData;
import net.qqxh.persistent.JfUserSimple;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author jason
 */
@Controller
public class mainController extends BaseController {
    @Autowired
    ShiroFilterFactoryBean shiroFilterFactoryBean;
    @Autowired
    JfSysUserData  jfSysUserData;
    @RequestMapping("/")
    public String index(ModelMap map) {
        JfUserSimple jfUserSimple = getLoginUser();
        if(jfUserSimple==null){
            jfUserSimple=new JfUserSimple();
        }
        map.addAttribute("permissions", "");
        map.addAttribute("jfShiroUser", jfUserSimple);
        if (SecurityUtils.getSubject().isAuthenticated()||SecurityUtils.getSubject().isRemembered()) {
            return "index";
        }

        return "login";
    }

    @GetMapping("/login")
    public String login() {
        if (SecurityUtils.getSubject().isAuthenticated()||SecurityUtils.getSubject().isRemembered()) {
            return "redirect:/";
        }
        return "login";
    }
    @PostMapping("/login")
    public String login(HttpServletRequest request,ModelMap map, @RequestParam(name = "username", required = false) String username, @RequestParam(name = "password", required = false) String password) {
       if(StringUtils.isEmpty(username)){
           return "login";
       }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            usernamePasswordToken.setRememberMe(true);
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
          e.printStackTrace();
            return "login";
        }

        return "redirect:/"  ;

    }
    @ResponseBody
    @RequestMapping("/changeTheme")
    public Object changeTheme(ModelMap map, @RequestParam(name = "theme", required = false) String theme) {
        JfUserSimple jfUserSimple = getLoginUser();
        if(jfUserSimple==null){
            return null;
        }
        jfUserSimple.setTheme(theme);
        JfUserSimple userdb=JfSysUserData.getUserByUserId(jfUserSimple.getUserid());
        userdb.setTheme(theme);
        return responseJsonFactory.getSuccessJson("修改主题成功","");
    }
    /**
     * 更新系统权限缓存数据方法。后台配置改变之后需要调用该方法进行刷新缓存信息
     */
    @RequestMapping("/updatePermission")
    @ResponseBody
    public Object updatePermission() {

        synchronized (shiroFilterFactoryBean) {

            AbstractShiroFilter shiroFilter = null;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean
                        .getObject();
            } catch (Exception e) {
                throw new RuntimeException(
                        "get ShiroFilter from shiroFilterFactoryBean error!");
            }

            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter
                    .getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver
                    .getFilterChainManager();

            // 清空老的权限控制
            manager.getFilterChains().clear();
            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            shiroFilterFactoryBean.setFilterChainDefinitionMap( jfSysUserData.getPermissions());
            // 重新构建生成
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim()
                        .replace(" ", "");
                manager.createChain(url, chainDefinition);
            }

        }
        return responseJsonFactory.getSuccessJson("刷新权限缓存成功","");
    }

}
